package com.beiming.libra.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.beiming.libra.common.Assert;
import com.beiming.libra.common.enums.ErrorCode;
import com.beiming.libra.common.enums.UserTypeEnum;
import com.beiming.libra.common.page.Page;
import com.beiming.libra.common.page.PageResult;
import com.beiming.libra.common.utils.BeanConvertUtils;
import com.beiming.libra.common.utils.CommonsUtils;
import com.beiming.libra.common.utils.Encrypt;
import com.beiming.libra.dao.ArbUserDetailMapper;
import com.beiming.libra.dao.UserDetailMapper;
import com.beiming.libra.dao.UserMapper;
import com.beiming.libra.domain.ArbUserDetail;
import com.beiming.libra.domain.User;
import com.beiming.libra.domain.UserDetail;
import com.beiming.libra.domain.dto.requestdto.ArbUserRequestDTO;
import com.beiming.libra.domain.dto.requestdto.ArbUserSearchRequestDTO;
import com.beiming.libra.domain.dto.requestdto.SecretaryGeneralUserRequestDTO;
import com.beiming.libra.domain.dto.requestdto.UserRegisterInfoRequestDTO;
import com.beiming.libra.domain.dto.responsedto.UserResponseDTO;
import com.beiming.libra.service.UserService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author weibo
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

  @Resource
  private UserMapper userMapper;
  @Resource
  private UserDetailMapper userDetailMapper;
  @Resource
  private ArbUserDetailMapper arbUserDetailMapper;

  @Override
  public UserResponseDTO getUserById(String userId) {
    UserResponseDTO dto = new UserResponseDTO();
    User user = userMapper.selectByPrimaryKey(userId);
    if (user == null)
      return null;
    dto.setUser(user);
    // 获取用户类型
    String userType = user.getUserType();
    // 仲裁员&办案秘书需要单独处理
    if (UserTypeEnum.ARBITRATION.getCode().equals(userType) || UserTypeEnum.SECRETARY.getCode().equals(userType)) {
      List<ArbUserDetail> arbList = arbUserDetailMapper.selectByUserId(userId);

      if (arbList.size() > 0) {
        dto.setArbDetail(arbList.get(0));
      }

    } else {
      List<UserDetail> detail = userDetailMapper.selectByUserId(userId);

      if (detail.size() > 0) {
        dto.setDetail(detail.get(0));
      }
    }

    return dto;
  }

  @Override
  public UserResponseDTO getUserByPhoneAndType(String phone, String type) {

    UserResponseDTO dto = new UserResponseDTO();
    List<User> userList = userMapper.selectByMobilePhoneAndType(phone, type);
    if (userList.size() <= 0)
      return null;
    User user = userList.get(0);
    String userId = user.getId();
    dto.setUser(user);
    // 获取用户类型
    String userType = user.getUserType();
    // 仲裁员&办案秘书需要单独处理
    if (UserTypeEnum.ARBITRATION.getCode().equals(userType) || UserTypeEnum.SECRETARY.getCode().equals(userType)) {
      List<ArbUserDetail> arbList = arbUserDetailMapper.selectByUserId(userId);
      if (arbList.size() > 0) {
        dto.setArbDetail(arbList.get(0));
      }
    } else {
      List<UserDetail> detail = userDetailMapper.selectByUserId(userId);
      if (detail.size() > 0) {
        dto.setDetail(detail.get(0));
      }
    }
    return dto;
  }

  @Override
  public List<UserResponseDTO> getAllUserByType(String type) {
    List<UserResponseDTO> list = new ArrayList<UserResponseDTO>();
    List<User> userList = userMapper.selectByType(type);
    for (User user : userList) {
      UserResponseDTO dto = new UserResponseDTO();
      String userId = user.getId();
      dto.setUser(user);
      // 获取用户类型
      String userType = user.getUserType();
      // 仲裁员&办案秘书需要单独处理
      if (UserTypeEnum.ARBITRATION.getCode().equals(userType) || UserTypeEnum.SECRETARY.getCode().equals(userType)) {
        List<ArbUserDetail> arbList = arbUserDetailMapper.selectByUserId(userId);
        if (arbList.size() > 0) {
          dto.setArbDetail(arbList.get(0));
        }
      } else {
        List<UserDetail> detail = userDetailMapper.selectByUserId(userId);
        if (detail.size() > 0) {
          dto.setDetail(detail.get(0));
        }
      }
      list.add(dto);
    }
    return list;
  }

  @Override
  public void insertListUser(List<User> userList, List<UserDetail> userDetails) {
    Assert.isListNotEmpty(userList, ErrorCode.ILLEGAL_PARAMETER);
    Assert.isListNotEmpty(userDetails, ErrorCode.ILLEGAL_PARAMETER);
    List<UserDetail> userDetailList = this.userDetailMapper.selectUserDetail(userDetails);
    List<User> users = this.userMapper.selectUser(userList);
    if (!CollectionUtils.isEmpty(userDetailList)) {
      Map<String, UserDetail> detailMap = userDetailList.stream()
          .collect(Collectors.toMap(detail -> detail.getCode(), Function.identity(), (detail1, detail2) -> detail1));
      List<UserDetail> userDetailList1 = userDetails.stream()
          .filter(userDetail -> detailMap.get(userDetail.getCode()) == null).collect(Collectors.toList());
      // 批量添加
      if (!CollectionUtils.isEmpty(userDetailList1)) {
        userDetailList1.addAll(userDetailList);
        // 添加消息
        this.userDetailMapper.insertUserDetailList(userDetailList1);
      }
    } else {
      // 批量添加
      this.userDetailMapper.insertUserDetailList(userDetails);
    }
    if (!CollectionUtils.isEmpty(users)) {
      Map<String, User> userMap = users.stream()
          .collect(Collectors.toMap(user -> user.getMobilePhone(), Function.identity(), (user1, user2) -> user1));
      List<User> userList1 = userList.stream().filter(userDetail -> userMap.get(userDetail.getMobilePhone()) == null)
          .collect(Collectors.toList());
      // 批量添加
      if (!CollectionUtils.isEmpty(userList1)) {
        this.userMapper.insertUserList(userList1);
      }
    } else {
      // 批量添加
      this.userMapper.insertUserList(userList);
    }
  }

  @Override
  public PageResult<ArbUserDetail> listArbUser(ArbUserSearchRequestDTO dto) {
    List<ArbUserDetail> list = arbUserDetailMapper.listUserByCond(dto.getUserType(), dto.getAddress(), dto.getAbility(),
        dto.getActualName(), (dto.getPageNo() - 1) * dto.getPageSize(), dto.getPageSize());
    PageResult<ArbUserDetail> pageResult = new PageResult<ArbUserDetail>();
    pageResult.setList(list);
    int total = arbUserDetailMapper.listUserByCondCount(dto.getUserType(), dto.getAddress(), dto.getAbility(),
        dto.getActualName());
    Page page = new Page();

    page.setPageNo(dto.getPageNo());
    page.setPageSize(dto.getPageSize());
    page.setTotalRecords(total);
    pageResult.setPage(page);
    return pageResult;
  }

  @Override
  public void insertArbUser(ArbUserRequestDTO dto) {
    // 获取前台参数
    String userType = dto.getUserType().getCode();
    String mobilePhone = dto.getMobilePhone();
    String password = dto.getPassword();
    // copy bean
    User userInfo = BeanConvertUtils.copyBean(dto, User.class);
    ArbUserDetail detail = BeanConvertUtils.copyBean(dto, ArbUserDetail.class);
    // 根据手机号和用户类型获取用户信息
    List<User> list = userMapper.selectByMobilePhoneAndType(mobilePhone, userType);
    // uuid主键
    String userId = CommonsUtils.get32BitUUID();
    // md5加密
    userInfo.setPassword(Encrypt.md5(password));
    // 如果有做更新操作，否则新增
    if (list.size() <= 0) {
      userInfo.setId(userId);
      userInfo.setUserType(userType);
      userMapper.insert(userInfo);
    } else {
      User user = list.get(0);
      userId = user.getId();
      userInfo.setId(userId);
      userMapper.updateByPrimaryKeySelective(userInfo);
    }
    // 根据用户id查询用户详情
    List<ArbUserDetail> detailList = arbUserDetailMapper.selectByUserId(userId);
    // 如果有做更新操作，否则新增
    if (detailList.size() <= 0) {
      detail.setId(CommonsUtils.get32BitUUID());
      detail.setUserId(userId);
      detail.setUserType(userType);
      arbUserDetailMapper.insert(detail);
    } else {
      ArbUserDetail arbUserDetail = detailList.get(0);
      String detailId = arbUserDetail.getId();
      detail.setId(detailId);
      detail.setUserType(userType);
      arbUserDetailMapper.updateByPrimaryKeySelective(detail);
    }

  }

  @Override
  public void insertGeneralUser(SecretaryGeneralUserRequestDTO dto) {
    // 获取前台参数
    String userType = dto.getUserType().getCode();
    String mobilePhone = dto.getMobilePhone();
    // 默认000000
    String password = "000000";
    // copy bean
    User userInfo = BeanConvertUtils.copyBean(dto, User.class);
    ArbUserDetail detail = BeanConvertUtils.copyBean(dto, ArbUserDetail.class);
    // 根据手机号和用户类型获取用户信息
    List<User> list = userMapper.selectByMobilePhoneAndType(mobilePhone, userType);
    // uuid主键
    String userId = CommonsUtils.get32BitUUID();
    // md5加密
    userInfo.setPassword(Encrypt.md5(password));
    // 如果有做更新操作，否则新增
    if (list.size() <= 0) {
      userInfo.setId(userId);
      userInfo.setUserType(userType);
      userMapper.insert(userInfo);
    } else {
      User user = list.get(0);
      userId = user.getId();
      userInfo.setId(userId);
      userMapper.updateByPrimaryKeySelective(userInfo);
    }
    // 根据用户id查询用户详情
    List<ArbUserDetail> detailList = arbUserDetailMapper.selectByUserId(userId);
    // 如果有做更新操作，否则新增
    if (detailList.size() <= 0) {
      detail.setId(CommonsUtils.get32BitUUID());
      detail.setUserId(userId);
      detail.setUserType(userType);
      arbUserDetailMapper.insert(detail);
    } else {
      ArbUserDetail arbUserDetail = detailList.get(0);
      String detailId = arbUserDetail.getId();
      detail.setId(detailId);
      detail.setUserType(userType);
      arbUserDetailMapper.updateByPrimaryKeySelective(detail);
    }

  }

  @Override
  public void insertUser(UserRegisterInfoRequestDTO dto) {

    // 获取前台参数
    String userType = dto.getUserType().getCode();
    String mobilePhone = dto.getMobilePhone();
    String emailCode = dto.getEmailCode();
    String email = dto.getEmail();
    // copy bean
    UserDetail userDetail = BeanConvertUtils.copyBean(dto, UserDetail.class);
    // 用户类型需要保存到用户详情表中
    userDetail.setUserType(userType);
    // 根据手机号和用户类型获取用户信息
    List<User> userList = userMapper.selectByMobilePhoneAndType(mobilePhone, userType);
    // 判断用户是否存在
    Assert.isListNotEmpty(userList, ErrorCode.USER_NOT_EXISTS);
    // 获取redis中邮件验证码
    String emailCodeRedis = "0";
    // 对比redis中的邮件验证码
    Assert.isTrue(emailCode.equals(emailCodeRedis), ErrorCode.EMAIL_CODE_IS_WRONG);

    User user = userList.get(0);
    String userId = user.getId();
    // 根据用户id查询用户详情信息
    List<UserDetail> detailList = userDetailMapper.selectByUserId(userId);
    if (detailList.size() > 0) {
      // 已存在用户详情做更新操作
      UserDetail detail = detailList.get(0);
      userDetail.setId(detail.getId());
      userDetailMapper.updateByPrimaryKeySelective(userDetail);
    } else {
      // 不存在用户详情做新增操作
      userDetail.setId(CommonsUtils.get32BitUUID());
      userDetail.setUserId(userId);
      userDetailMapper.insert(userDetail);
    }

  }

}
